package com.scholarship.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.scholarship.system.common.constants.SystemConstants;
import com.scholarship.system.common.dto.Result;
import com.scholarship.system.common.exception.BusinessException;
import com.scholarship.system.entity.Student;
import com.scholarship.system.entity.User;
import com.scholarship.system.mapper.StudentMapper;
import com.scholarship.system.mapper.UserMapper;
import com.scholarship.system.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 学生服务实现类
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<List<Map<String, Object>>> getStudentList(Long advisorId, String keyword) {
        // 构建SQL查询，联表查询student和user
        List<Map<String, Object>> studentList = studentMapper.selectStudentList(advisorId, keyword);
        return Result.success(studentList);
    }

    @Override
    public Result<Map<String, Object>> getStudentDetail(Long id) {
        // 查询学生信息
        Student student = studentMapper.selectById(id);
        if (student == null) {
            return Result.error("学生不存在");
        }

        // 查询用户基本信息
        User user = userMapper.selectById(student.getUserId());
        if (user == null) {
            return Result.error("用户信息不存在");
        }

        // 组装数据
        Map<String, Object> studentDetail = new HashMap<>();
        studentDetail.put("id", student.getId());
        studentDetail.put("userId", user.getId());
        studentDetail.put("studentId", student.getStudentId());
        studentDetail.put("name", user.getName());
        studentDetail.put("gender", user.getGender());
        studentDetail.put("phone", user.getPhone());
        studentDetail.put("email", user.getEmail());
        studentDetail.put("college", student.getCollege());
        studentDetail.put("major", student.getMajor());
        studentDetail.put("grade", student.getGrade());
        studentDetail.put("className", student.getClassName());
        studentDetail.put("entryYear", student.getEntryYear());
        studentDetail.put("educationLevel", student.getEducationLevel());
        studentDetail.put("advisorId", student.getAdvisorId());

        return Result.success(studentDetail);
    }

    @Override
    @Transactional
    public Result<Void> addStudent(Student student, Map<String, Object> userInfo) {
        // 1. 检查学号是否已存在
        LambdaQueryWrapper<Student> studentWrapper = new LambdaQueryWrapper<>();
        studentWrapper.eq(Student::getStudentId, student.getStudentId());
        if (studentMapper.selectCount(studentWrapper) > 0) {
            return Result.error("学号已存在");
        }

        // 2. 创建用户账号
        User user = new User();
        user.setUsername(student.getStudentId()); // 用学号作为用户名
        user.setPassword(SystemConstants.DEFAULT_PASSWORD); // 使用默认密码
        user.setName((String) userInfo.get("name"));
        user.setRole(SystemConstants.ROLE_STUDENT);
        user.setGender((String) userInfo.get("gender"));
        user.setPhone((String) userInfo.get("phone"));
        user.setEmail((String) userInfo.get("email"));

        userMapper.insert(user);

        // 3. 创建学生信息
        student.setUserId(user.getId());
        studentMapper.insert(student);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> updateStudent(Student student, Map<String, Object> userInfo) {
        // 1. 检查学生是否存在
        Student existStudent = studentMapper.selectById(student.getId());
        if (existStudent == null) {
            return Result.error("学生不存在");
        }

        // 2. 如果修改了学号，检查新学号是否已存在
        if (!existStudent.getStudentId().equals(student.getStudentId())) {
            LambdaQueryWrapper<Student> studentWrapper = new LambdaQueryWrapper<>();
            studentWrapper.eq(Student::getStudentId, student.getStudentId())
                    .ne(Student::getId, student.getId());
            if (studentMapper.selectCount(studentWrapper) > 0) {
                return Result.error("学号已存在");
            }
        }

        // 3. 更新用户信息
        User user = userMapper.selectById(existStudent.getUserId());
        if (user != null) {
            user.setUsername(student.getStudentId()); // 更新用户名为学号
            user.setName((String) userInfo.get("name"));
            user.setGender((String) userInfo.get("gender"));
            user.setPhone((String) userInfo.get("phone"));
            user.setEmail((String) userInfo.get("email"));
            userMapper.updateById(user);
        }

        // 4. 更新学生信息
        studentMapper.updateById(student);

        return Result.success();
    }

    @Override
    @Transactional
    public Result<Void> deleteStudent(Long id) {
        // 1. 检查学生是否存在
        Student student = studentMapper.selectById(id);
        if (student == null) {
            return Result.error("学生不存在");
        }

        // 2. 删除学生信息
        studentMapper.deleteById(id);

        // 3. 删除用户账号
        userMapper.deleteById(student.getUserId());

        return Result.success();
    }

    @Override
    public Result<Void> assignAdvisor(Long studentId, Long advisorId) {
        // 1. 检查学生是否存在
        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            return Result.error("学生不存在");
        }

        // 2. 检查导师是否存在（如果advisorId不为null）
        if (advisorId != null) {
            User advisor = userMapper.selectById(advisorId);
            if (advisor == null || !SystemConstants.ROLE_TEACHER.equals(advisor.getRole())) {
                return Result.error("导师不存在");
            }
        }

        // 3. 更新学生的导师ID
        student.setAdvisorId(advisorId);
        studentMapper.updateById(student);

        return Result.success();
    }
}